import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
import numpy as np
from tensorflow.keras.models import load_model
from sklearn.preprocessing import StandardScaler
import pandas as pd
import sqlite3
import sys
import subprocess

DATABASE = 'users.db'

def get_user_predictions(user_id):
    with sqlite3.connect(DATABASE) as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT constructionTime, square, livingRoom, drawingRoom, kitchen, bathRoom, floor, subway, prediction FROM history WHERE user_id=?", (user_id,))
        records = cursor.fetchall()
        return records

class HousePricePredictor(tk.Tk):
    def __init__(self, user_id):
        super().__init__()
        self.user_id = user_id
        self.title("北京房价预测器")
        self.geometry("300x500")
        self.model = load_model("price_model.h5")
        self.scaler = StandardScaler()

        dummy_data = pd.DataFrame(
            {
                "constructionTime": [2000, 2024],
                "square": [1, 200],
                "livingRoom": [1, 5],
                "drawingRoom": [1, 2],
                "kitchen": [1, 3],
                "bathRoom": [1, 3],
                "floor": [1, 30],
                "subway": [0, 1],
            }
        )
        self.scaler.fit(dummy_data)

        self.create_widgets()

    def create_widgets(self):
        tk.Label(self, text="建造年份 (Year)", font=("宋体", 12, "bold")).pack()
        self.constructionTime = tk.Entry(self)
        self.constructionTime.pack()

        tk.Label(self, text="面积 (m²)", font=("宋体", 12, "bold")).pack()
        self.square = tk.Entry(self)
        self.square.pack()

        tk.Label(self, text="卧室数量", font=("宋体", 12, "bold")).pack()
        self.livingRoom = tk.Entry(self)
        self.livingRoom.pack()

        tk.Label(self, text="客厅数量", font=("宋体", 12, "bold")).pack()
        self.drawingRoom = tk.Entry(self)
        self.drawingRoom.pack()

        tk.Label(self, text="厨房数量", font=("宋体", 12, "bold")).pack()
        self.kitchen = tk.Entry(self)
        self.kitchen.pack()

        tk.Label(self, text="浴室数量", font=("宋体", 12, "bold")).pack()
        self.bathRoom = tk.Entry(self)
        self.bathRoom.pack()

        tk.Label(self, text="楼层", font=("宋体", 12, "bold")).pack()
        self.floor = tk.Entry(self)
        self.floor.pack()

        tk.Label(self, text="地铁 (是/否)", font=("宋体", 12, "bold")).pack()
        self.subway_var = tk.IntVar()
        self.subway = ttk.Checkbutton(self, text="是否有地铁", variable=self.subway_var)
        self.subway.pack()

        self.predictButton = tk.Button(self, text="预测房价", command=self.predict_price, font=("宋体", 12, "bold"))
        self.predictButton.pack()

        self.historyButton = tk.Button(self, text="查看历史记录", command=self.show_history, font=("宋体", 12, "bold"))
        self.historyButton.pack()

        self.resultLabel = tk.Label(self, text="", font=("宋体", 15, "bold"))
        self.resultLabel.pack()

    def predict_price(self):
        try:
            features = np.array(
                [
                    [
                        int(self.constructionTime.get()),
                        float(self.square.get()),
                        int(self.livingRoom.get()),
                        int(self.drawingRoom.get()),
                        int(self.kitchen.get()),
                        int(self.bathRoom.get()),
                        int(self.floor.get()),
                        self.subway_var.get(),
                    ]
                ]
            )

            features = self.scaler.transform(features)
            prediction = self.model.predict(features)
            price = prediction[0][0]

            prediction_text = f"预测房价: {price:.2f} 元/㎡"
            self.resultLabel.config(text=prediction_text)

            self.save_prediction(
                int(self.constructionTime.get()),
                float(self.square.get()),
                int(self.livingRoom.get()),
                int(self.drawingRoom.get()),
                int(self.kitchen.get()),
                int(self.bathRoom.get()),
                int(self.floor.get()),
                self.subway_var.get(),
                prediction_text
            )

        except ValueError as e:
            messagebox.showwarning("输入错误", "请输入所有字段的有效值。")

    def save_prediction(self, constructionTime, square, livingRoom, drawingRoom, kitchen, bathRoom, floor, subway, prediction):
        with sqlite3.connect(DATABASE) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO history (user_id, constructionTime, square, livingRoom, drawingRoom, kitchen, bathRoom, floor, subway, prediction) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                (self.user_id, constructionTime, square, livingRoom, drawingRoom, kitchen, bathRoom, floor, subway, prediction)
            )
            conn.commit()

    def show_history(self):
        predictions = get_user_predictions(self.user_id)
        history_window = tk.Toplevel(self)
        history_window.title("历史记录")
        history_window.geometry("1000x400")

        tk.Label(history_window, text="您的历史预测记录:", font=("宋体", 12, "bold")).pack()
        for record in predictions:
            tk.Label(history_window, text=f"建造年份: {record[0]}, 面积: {record[1]}, 卧室: {record[2]}, 客厅: {record[3]}, 厨房: {record[4]}, 浴室: {record[5]}, 楼层: {record[6]}, 地铁: {'有' if record[7] else '无'}, 价格: {record[8]}", font=("宋体", 12)).pack()


if __name__ == "__main__":
    try:
        user_id = int(sys.argv[1])
    except (IndexError, ValueError):
        user_id = 1
    app = HousePricePredictor(user_id)
    app.mainloop()
